package kr.co.dcinside.agitater;

import java.util.HashMap;

/**
 * @author bkm0714
 */
public class IPv4
{
    private static final String PEROID = ".";
    private static HashMap< String, IPv4 > internalMap = new HashMap< String, IPv4 >();
    private final byte lev1;
    private final byte lev2;
    private final byte lev3;
    private final byte lev4;

    private IPv4( byte lev1, byte lev2, byte lev3, byte lev4 )
    {
        this.lev1 = lev1;
        this.lev2 = lev2;
        this.lev3 = lev3;
        this.lev4 = lev4;
    }

    public static IPv4 getInstance( String ipv4 )
    {
        String[] splited = split( ipv4 );
        return new IPv4( Byte.parseByte( splited[0] ), Byte
            .parseByte( splited[1] ), Byte.parseByte( splited[2] ), Byte
            .parseByte( splited[3] ) );

    }

    private static String[] split( String ipv4 )
    {
        return ipv4.split( "\\." );
    }

    public static IPv4 getInstance( byte lev1, byte lev2, byte lev3, byte lev4 )
    {
        IPv4 result;

        String key = buildKey( lev1, lev2, lev3, lev4 );
        if ( internalMap.containsKey( key ) )
        {
            result = internalMap.get( key );
        }
        else
        {
            result = new IPv4( lev1, lev2, lev3, lev4 );
            internalMap.put( key, result );

        }
        return result;
    }

    private static String buildKey( byte lev1, byte lev2, byte lev3, byte lev4 )
    {
        StringBuilder sb = new StringBuilder();
        sb.append( lev1 );
        sb.append( PEROID );
        sb.append( lev2 );
        sb.append( PEROID );
        sb.append( lev3 );
        sb.append( PEROID );
        sb.append( lev4 );

        return sb.toString();
    }

    public byte getLev1()
    {
        return lev1;
    }

    public byte getLev2()
    {
        return lev2;
    }

    public byte getLev3()
    {
        return lev3;
    }

    public byte getLev4()
    {
        return lev4;
    }
}